[第六週] CSS Part1 - Selector


CSS 是什麼?

Cascading Style Sheets 階層式樣式表
MDN上定義: CSS 既非標準程式語言,也不是標記語言, 而是一種風格頁面語言(style sheet language):它能讓你在 HTML 文件中的元素(element)上套用不同的頁面樣式(style)。

如何使用

  1. 開啟一個 .css 檔案並在裡面編輯,如:
    div {
     background: black;
    }
    
  2. 打開 .html 文件,然後將下列程式碼貼到 head,也就是 <head></head> 標籤間。
    <link rel="stylesheet" href="styles/style.css">

    • 針對全部的 html 做樣式編輯,加上*
      Universal Selectors
    • 針對標籤編輯
      div {
      background: red;
      }
      body {
      background: yellow;
      }
      
    • 針對 id 與 class 編輯, id 用 # ; class 用 .
      // .html
      <div id="div1">
      <div class="animal"
      
      // .css
      #div1 {
      background: red;
      }
      .animal {
      background: yellow;
      }
      
    • 同時符合多個條件, 用 . 連結
      /// 滿足 div, 又滿足 class: "animal" "text-black"
      div.animal.text-black
      
    • 旁邊那個用 + ; 旁邊全部用 ~ ,必須是同一層的才可以選得到

      // .css
      // 編輯 bg-red 旁的那個 bg-red 
      .bg-red + .bg-red {
      background: red;
      }
      // 編輯 div 旁所有的 span
      div ~ span {
      background: yellow;
      }
      

    • Pseudo-classes : 滑鼠移到字上會變顏色為例(hover)

    span:hover {
      background:red;
    }
    

    更多效果參考請點我

    • 針對第n個元素做編輯,nth-child

      // .css
      // 對 class wrapper 裡的第 2 個 div 做背景顏色的編輯
      .wrapper div:nth-child(2) {
        background: red;
      }  
      // 對 class wrapper 裡的奇數項 div 做背景顏色的編輯
      .wrapper div:nth-child(odd) {
        background: red;
      }
      // 對 class wrapper 裡的第 3n + 1 項 div 做背景顏色的編輯
      .wrapper div:nth-child(3n +1) {
        background: red;
      }
      
    • Pseudo - elements 偽元素

      // .css
      // 用 2 個冒號,後接偽元素
      .wrapper::before {
        content: "123";
        color:red;
      }
      
      // .html
      <div class="price" data-symbol="NTD">
      1000
      </div>
      // .css
      // 在 attr 裡可以取到該屬性裡的值
      .price::after {
        content: attr(data-symbol); 
        }
      // 輸出為
      1000 NTD
      
    • CSS Selector 的權重
      id > class > 標籤,越詳細的贏
      但以上都輸給 inline style,即在 html 裡寫上想要的樣式
      奧義: !important,會直接用這個的樣式
      延伸閱讀:
      1. 強烈推薦收藏好物 – CSS Specificity (CSS 權重一覽)
      2. 你對 CSS 權重真的足夠了解嗎?
#css selector






你可能感興趣的文章

耦合過多的缺點

耦合過多的缺點

The introduction and difference between class component and function component in React

The introduction and difference between class component and function component in React

Day 48 - Selenium & Cookie Click Game

Day 48 - Selenium & Cookie Click Game






留言討論